//
//  HJUserAccountViewModel.swift
//  Weibo
//
//  Created by 韩佳 on 16/4/19.
//  Copyright © 2016年 ddg. All rights reserved.
//

import UIKit
import SVProgressHUD

class HJUserAccountViewModel: NSObject {
    //单例
    static let shareAccount: HJUserAccountViewModel = HJUserAccountViewModel()
    //初始化的时候就从文档中读取信息
    override init() {
        super.init()
        account = accountInSanbox()
//        print(account?.access_token)
//        print(account?.expiresDate)
    }
    var account:HJUserAccount?
    
    var accessToken: String? {
        return self.account?.access_token
    }
    //用一个属性判断用户是否登录
    var isLogin: Bool{
        if accessToken == nil{
            return false
        }
        //判断access_token是否过期
//        print(account?.expiresDate)
        guard let expiresDate = account?.expiresDate else{
            
            return false
        }
        if NSDate().compare(expiresDate) == .OrderedAscending{
//            print(expiresDate)
            return true
        }
        return false
    }
    
    //获取AccessToken
    func loadAccessToken(code: String, finish: ((isSuccess:Bool) -> ())){
        let URLString = "https://api.weibo.com/oauth2/access_token"
        let param = [
            "client_id": WB_APP_KEY,
            "client_secret": WB_APP_SECRET,
            "grant_type":"authorization_code",
            "code": code,
            "redirect_uri":WB_REDIRECT_URI
        ]
        
        
        HJNetworkTools.shareTools.request(HJRequestMethod.Post, urlString: URLString, parameters: param) { (responseObject, error) -> () in
            if error != nil {
                print(error)
                finish(isSuccess: false)
                return
            }
//            print("请求成功--\(responseObject)")
            guard let dict = responseObject as? [String: AnyObject] else{
                print("服务器数据类型错误")
                finish(isSuccess: false)
                return
            }
            //转模型
            let account = HJUserAccount(dict: dict)
//                        print("转模型--\(account.expiresDate)")
            //获取个人信息
            self.loadUserInfo(account,finish: finish)
        }
    }
    //从网络获取个人信息
    private func loadUserInfo(account: HJUserAccount, finish: ((isSuccess:Bool) -> ())){
        let urlString = "https://api.weibo.com/2/users/show.json"
        
        let param = [
            "access_token": account.access_token ?? "",
            "uid": account.uid ?? ""
        ]
        
        HJNetworkTools.shareTools.request(HJRequestMethod.Get, urlString: urlString, parameters: param) { (responseObject, error) -> () in
            if error != nil {
                SVProgressHUD.showErrorWithStatus("网络错误")
                finish(isSuccess: false)
            }
            
            guard let dict = responseObject as? [String: AnyObject] else{
                print("服务器数据类型错误")
                finish(isSuccess: false)
                return
            }
            //            print(dict)
            account.name = dict["name"] as? String
            account.avatar_large = dict["avatar_large"] as? String
            self.account = account
            //保存用户信息
            self.saveuserInfo(account)
            //回调
            finish(isSuccess: true)

        }
        
    }
    //归档
    private func saveuserInfo(account: HJUserAccount){
        let path = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("account.plist")
//        print(path)
//        print(account)
        NSKeyedArchiver.archiveRootObject(account, toFile: path)
    }
    //解档
    private func accountInSanbox()-> HJUserAccount?{
        let path = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("account.plist")
        let result = NSKeyedUnarchiver.unarchiveObjectWithFile(path) as? HJUserAccount
        return result
    }
}
